package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"shuqi-novel/models/mysql"

	"shuqi-novel/novelrpc/internal/svc"
	"shuqi-novel/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type NovelUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewNovelUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NovelUpdateLogic {
	return &NovelUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *NovelUpdateLogic) NovelUpdate(in *novelrpc.NovelUpdateRequest) (*novelrpc.NovelUpdateResponse, error) {
	// todo: add your logic here and delete this line

	var findNovel mysql.Novel
	mysql.DB.Debug().Where("id = ?", in.NovelId).Find(&findNovel)

	if findNovel.ID == 0 {
		return nil, fmt.Errorf("当前小说不存在")
	}

	if findNovel.UserId != in.UserId {
		return nil, fmt.Errorf("当前小说不属于自己,无权限修改")
	}

	novel := mysql.Novel{
		Model: gorm.Model{ID: uint(in.NovelId)},
		Title: in.Title,
		Image: in.Image,
	}

	mysql.DB.Updates(&novel)

	return &novelrpc.NovelUpdateResponse{
		NovelId: int64(novel.ID),
	}, nil
}
